<?php
namespace app\common\business;

use app\common\model\mysql\Goods as goodsModel;
use app\common\business\GoodsSku as goodsSkuBusi;
use app\common\business\Category as categoryBusi;
use app\common\business\SpecsValue as specsValueBusi;
use think\facade\Cache;
class Goods extends BusiBase{
	protected $model = null;
	public function __construct(){
		$this->model = new goodsModel();
	}
 
	// 添加商品数据
	public function insertData($data){
		$goodsId = $this->add($data);
		//dump($goodsId);exit;
		if(!$goodsId){
			return $goodsId;
		}

		//数据入sku表
		//如果是统一规格
		if($data['goods_specs_type']==1){
			$goodsSkuData = [
				'goods_id'=>$goodsId,
			];
			//todo 插入数据
			return true;
		}elseif($data['goods_specs_type']==2){//多规格
			$data['goods_id'] = $goodsId;
			$res = (new goodsSkuBusi())->saveAll($data);
			if(!empty($res)){
				//总库存
				$stock = array_sum(array_column($res, 'stock'));
				$goodsUpdateData = [
					'price'=>$res[0]['price'],
					'cost_price'=>$res[0]['cost_price'],
					'sku_id'=>$res[0]['id'],
					'stock'=>$stock,
				];
				$goodsRes = $this->model->updateById($goodsId,$goodsUpdateData);
				if(!$goodsRes){
					throw new \think\Exception("goods表更新数据失败");
				}
			}else{
				throw new \think\Exception("sku表添加入库失败");
				
			}
		}

		return true;
	}

	//获取商品列表
	public function getLists($data,$num){
		$likeKeys = [];
		if(!empty($data)){
			$likeKeys = array_keys($data);
			//echo '<pre>';print_r($likeKeys);
		}
		try{
			$list = $this->model->getLists($likeKeys,$data,$num);
			$result = $list->toArray();
			//halt($result);
		}catch(\Exception $e){
			$result = [
				'total'=>0,
				'per_page'=>$num,
				'current_page'=>1,
				'last_page'=>0,
				'data'=>[]
			];
		}
		return $result;

	}

	// 根据ID获取记录
	public function getById($id){
		$result = $this->categoryObj->find($id);
		if(empty($result)){
			return [];
		}
		return $result->toArray();
	}

	//获取论循图片
	public function getRotationChart(){
		//条件
		$data = [
			'is_index_recommend'=>1,
		];
		//显示字段
		$field = "sku_id as id,title,big_image as image";
		try{
			$result = $this->model->getNormalGoodsByCondition($data,$field);
		}catch(\Exception $e){echo 11;
			$result = [];
		}

		return $result->toArray();
	}
	//栏目下商品推荐
	public function categoryGoodsRecommend($categoryIds){
		if(empty($categoryIds)){
			return [];
		}
		//栏目的获取
		foreach($categoryIds as $k=>$v){
			//$result[$k]['categorys'] = [];
			$result[$k]['categorys'] = $this->getNormalCategoryById($v,$categoryIds);
		}
		/*
		$where = [
			['id','in',$categoryIds]
		];
		$field = "id as category_id,name,icon";
		$categoryIds = (new categoryBusi())->getNormalCategorys2($where,$field);
		//halt($categoryIds);
		echo '<pre>';print_r($categoryIds);exit;
		foreach($categoryIds as $k=>$v){
			//$result[$k]['categorys'] = [];
			$field = "id as category_id,name";
			//$result[$k]['categorys'] = (new categoryBusi())->getNormalByPid($v['category_id'],$field);

			$res=(new categoryBusi())->getNormalByPid($v['category_id'],$field);
			halt($res);
		}
		*/
		foreach($categoryIds as $k=>$v){
			$result[$k]['goods'] = $this->getNormalGoodsFindInSetCategoryId($v);
		}
		return $result;
	}

	public function getNormalGoodsFindInSetCategoryId($categoryId){
		$field = "sku_id as id,title,price,recommend_image as image";
		try{
			$result = $this->model->getNormalGoodsFindInSetCategoryId($categoryId,$field);
		}catch(\Exception $e){
			$result = [];
		}
		return $result->toArray();
	}

	public function getNormalCategoryById($categoryId,$categoryIds){
		$category = (new categoryBusi())->getById($categoryId);
		$pid = $category['pid'];
		$category2 = (new categoryBusi())->getById($pid);
		//halt($category2);
		$cateArr2['category_id']=$category2['id'];
		$cateArr2['name']=$category2['name'];

		$where = [
			['id','in',$categoryIds]
		];
		$field = "id as category_id,name";
		$category = (new categoryBusi())->getNormalCategorys2($where,$field);
		$cateArr2['list'] = $category;
		return $cateArr2;
	}

	public function getNormalLists($data,$num=5,$order){
		try{
			$field = 'sku_id as id,title,recommend_image as image,price';
			$list = $this->model->getNormalLists($data,$num,$field,$order);
			$res = $list->toArray();
			$result = [
				'total_page_num' => $res['last_page'] ?? 0,
				'count' => $res['total'] ?? 0,
				'page' => $res['current_page'] ?? 0,
				'page_size' => $num,
				'list' => $res['data'] ?? 0,
			];
		}catch(\Exception $e){
			echo $e->getMessage();exit;
			$result = [];
		}

		return $result;
	}

	//商品详情
	public function getGoodsDetailBySkuId($skuId){
		$goodsSkuBusi = new goodsSkuBusi();
		$goodsSku = $goodsSkuBusi->getNormalSkuAndGoods($skuId);
		if(!$goodsSku){
			return [];
		}
		if(empty($goodsSku['goods'])){
			return [];
		}
		$goods = $goodsSku['goods'];
		$skus = $goodsSkuBusi->getSkusByGoodsId($goods['id']);
		//halt($skus);
		if(!$skus){
			return [];
		}
		//dump($skus);exit;
		$flagVal = '';
		foreach ($skus as $key => $value) {
			if($value['id'] == $skuId){
				$flagVal = $value['specs_value_ids'];
			}
		}
		$gids = array_column($skus, "id","specs_value_ids");
		$sku = [];
		$sku = (new specsValueBusi())->dealGoodsSkus($gids,$flagVal);
		$result = [
			'title' => $goods['title'],
			'price' => $goodsSku['price'],
			'cost_price' => $goodsSku['cost_price'],
			'stock' => $goodsSku['stock'],
			'gids' => $gids,
			'image' => $goods['carousel_image'],
			'sku' => $sku,
			'detail' => [
				'd1' => [
					'商品编码' => $goodsSku['id'],
					'上架时间' => $goods['create_time'],
				],
				'd2' => preg_replace('/(<img.+?src=")(.*?)/', '$1'.request()->domain().'$2', $goods['description']),
			],
		];
		//halt($result);
		Cache::inc('mall_pv_'.$goods['id']);
		return $result;
	}
}